#!/usr/bin/python
# -*- coding: utf-8 -*-
import gluon.contrib.simplejson as json
exec("import applications.%s.modules.apihelper as api" % request.application)

def index(): return dict(message="hello from api.py")

#process twitter
def process_twitter():
        #this needs to have a message queue &
        #inbox & outbox; but for now, it will just be single function
        try:
                yatsy_config=db().select(db.config.ALL)
                config_id=yatsy_config[0]['id'] 
                twitter_id=yatsy_config[0]['twitter_id']
                twitter_pwd=yatsy_config[0]['twitter_pwd']
                twitter_since=yatsy_config[0]['last_twitter_intime']
                twitter_dm_id=yatsy_config[0]['last_dm_id']
                #all twitter msg are created in the name of user@example.com
                #this needs to be changed to the user who sends the twitter
                uid = db(db.auth_user.email=='user@example.com').select(db.auth_user.ALL)[0].id
                                
                ret_dict={}
                
                exec("import applications.%s.modules.twitter as twitter" % request.application)
                twitapi = twitter.Api(username=twitter_id, password=twitter_pwd)
                dms = twitapi.GetDirectMessages(since_id=twitter_dm_id)
                #print 'DMs rxed %s' % str(len(dms))
                for dm in dms:
                        sender_name = dm.sender_screen_name
                        dm_id = dm.id
                        txt = dm.text
                        
                        #print '%s rxed from %s' % (txt, sender_name)
                        amt,paid_by,desc=txt.split(';')                       
                        #insert a ei record
                        import datetime
                       	api.add_expense(db=db,
							record_date=datetime.datetime.now().strftime('%Y-%m-%d'), 
            				description=desc, 
            				amount=amt,
            				paid_by=paid_by,
            				category=1,
            				created_on=request.now,
            				created_by=uid,
            				created_via='twitter'
						)                     
                        #store the id
                        db(db.config.id==config_id).update(last_dm_id=dm_id)
                        
                        #reply back
                        reply_msg='@%s Your EITracker update is done' % sender_name
                        #print reply_msg
                        st=twitapi.PostUpdate(reply_msg)
                        #print st.text
                ret_dict=dict(id=0, msg='success')
        except Exception,e:
                ret_dict=dict(id=1,msg=str(e))
        return json.dumps(ret_dict)